package com.example.administrator.exkotlin.coroutine.net

import android.util.Log
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.io.IOException
import java.util.concurrent.TimeUnit

/**
 * Author by lp,on 2020/8/27/027,11:19.
 * 防止反复创建
 */
object RetrofitCreator {
    private const val BASE_URL = "http://www.kuaidi100.com"

    //拦截者
    private val headerInterceptor = object : Interceptor {
        @Throws(IOException::class)
        override fun intercept(chain: Interceptor.Chain): Response {
            val request = chain.request().newBuilder().build()
            Log.i("RetrofitCreator", "request body : $request")
            return chain.proceed(request)
        }
    }

    //okHttpClient
    val client = OkHttpClient.Builder().addInterceptor(headerInterceptor)
            .connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS).build()

    private val retrofit = Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())
            .build()


    private fun <T> create(serviceClass: Class<T>): T = retrofit.create(serviceClass)

    val speedService by lazy { create(SpeedService::class.java) }


}

